如何避免使用 FirstOrDefault 未將對象引用設置為對象錯誤的實例? (How to avoid Object reference not set to instance of object error with FirstOrDefault?)


問題描述

如何避免使用 FirstOrDefault 未將對象引用設置為對象錯誤的實例? (How to avoid Object reference not set to instance of object error with FirstOrDefault?)

這是我的班級:

public class Employee
{
     public int EmployeeId { get; set; }
     public int Skillssetpoints { get; set; }
     public string Name { get; set; }
     public string EmployeeCode { get; set; }
     public Nullable<System.DateTime> Date { get; set; }
}

代碼:

場景1

var data=context.Employee.ToList();  //Get all employee records.

//Filter records by employee code(Emp01) and fetch single employee code.for eg:Emp01

var empCode = data.FirstOrDefault(t =>(t.EmployeeCode.Trim() == Model.EmployeeCode.Trim())).EmployeeCode;

在這裡,如果找不到與 Emp01 匹配的內容,則獲取錯誤對象引用未設置為對象實例但使用以下代碼修復此問題:

var Single = data.FirstOrDefault(t =>(t.EmployeeCode.Trim() == Model.EmployeeCode.Trim()));

if(single!=null)
{
   var data=Single.EmployeeCode;
   //Rest other code.
}

場景 2:

var data=context.Employee.ToList();  //Get all employee records.

//Fetch List of employee with Employee code:Emp01

var list= data.FirstOrDefault(t =>(t.EmployeeCode.Trim() == Model.EmployeeCode.Trim()));

在我的數據對像中,如果任何 EmployeeCodenull 那麼我收到此錯誤:

錯誤:對象引用未設置為對象實例

已修復:

var list= data.FirstOrDefault(t => (t.EmployeeCode != null) && (t.EmployeeCode.Trim() == Model.EmployeeCode.Trim()));

對於我的第二種情況,當我獲取員工的所有記錄並按員工代碼進行過濾時,我一開始沒有添加此空條件,因為我擁有所有員工記錄而沒有任何空員工代碼,並且一切正常,但在任何時候員工代碼變為 null 並得到了這個錯誤。所以將來我想避免這個錯誤。

所以我只想知道有沒有更好的方法來處理這兩種情況???

/p>/p>

參考解法

方法 1:

For scenario 1, you can write something like this:

var employees = context.Employee.ToList();
var data = employees.Where(t => t.EmployeeCode.Trim() == Model.EmployeeCode.Trim())
                    .Select(t => t.EmployeeCode)
                    .FirstOrDefault();

if(data != null)
{
   //Rest other code.
}

For scenario 2, you can add an extra where to filter out nulls. However way you slice it, you will need to check, but splitting up the filtering is nicer, at least in my opinion:

var list= data
          .Where(d => d != null)
          .FirstOrDefault(t => t.EmployeeCode.Trim() == Model.EmployeeCode.Trim());

方法 2:

var employees = context.Employee.ToList();
var result = employees.Where(t => (t.EmployeeCode ?? "").Trim() == (Model.EmployeeCode ?? "").Trim())
                    .Select(t => t.EmployeeCode).FirstOrDefault();

(by Learning‑Overthinker‑ConfusedRobPalanikumar)

參考文件

  1. How to avoid Object reference not set to instance of object error with FirstOrDefault? (CC BY‑SA 2.5/3.0/4.0)

#linq #.net #asp.net-mvc #C#






相關問題

System.Linq.Expressions.Expression<Func<TSource,TKey>> 中的 TKey 是什麼? (What is TKey in System.Linq.Expressions.Expression<Func<TSource,TKey>>?)

查詢未與其他某些特定實體連接的實體 (Query for entities which are not joined with some other certain entities)

使用 LINQ 讀取 C# XML (C# XML reading using LINQ)

Linq 在測試期間出錯,但不是運行時 (Error with Linq during testing, but not runtime)

如何避免使用 FirstOrDefault 未將對象引用設置為對象錯誤的實例? (How to avoid Object reference not set to instance of object error with FirstOrDefault?)

如何使用 LINQ 從 SQL Server 獲取唯一的名稱首字母和以該字母開頭的名稱計數? (How to get unique First Letter of names and count of names starting with that letter from SQL Server using LINQ?)

幫助 Linq 和泛型。在查詢中使用 GetValue (Help with Linq and Generics. Using GetValue inside a Query)

用於從 List(Of ) 中刪除一列的 LINQ 查詢 (LINQ Query for deleting one column from List(Of ))

在一個返回的字段上選擇不同的 (Select distinct on one returned field)

更新 Linq 查詢返回的結果集中的列值 (Updating a column value in resultset returned by a Linq query)

如何使用 LINQ 使用聯合查詢從多個表中進行選擇以僅返回一列? (How to select from multiple tables using LINQ using a union query to return only one column?)

Linq 加入到與 Entity Framework Core 的 1:n 關係 (Linq join to 1:n relation with Entity Framework Core)







留言討論